import React, {useState, useEffect} from 'react'
import {useDispatch, useSelector} from 'react-redux'
import {handleArticleList, handleDelArticle} from '@/store2/actions'
import './article.scss'
import MySelectOptions from '@/component/selectOption/MySelectOptions'
import moment from 'moment'
import {statusArr} from '@/common/cateStatus'
import {PROXY_URL} from '@/common/constant'
import { 
  Row, 
  Col, 
  Divider,
  Input,
  Button,
  Table,
} from 'antd'
import {PlusOutlined} from '@ant-design/icons' 

export default props => {
  let defaultFormState = {
    title: '',
    cate: '',
    page: 1,
    limit: 3
  }
  const dispatch = useDispatch()
  const articleList = useSelector(store => store.article.articleList)
  const articleCates = useSelector(store => store.article.articleCates)
  const delId = useSelector(store => store.article.delId)
  const [formState, setFormState] = useState(defaultFormState)
  const [selectedRowKeys, setSelectedRowKeys] = useState([])

  //表头
  const columns = [
    {
      title: '作者',
      dataIndex: 'author',
      align: 'center',
    },
    {
      title: '标题',
      dataIndex: 'title',
      align: 'center',
    },
    {
      title: '封面',
      dataIndex: 'img',
      align: 'center',
      render: img => <img alt="封面" style={{width: 80, height: 80}} src={PROXY_URL + img} />
    },
    {
      title: '类别',
      dataIndex: 'cate',
      align: 'center',
      render: cate => articleCates && articleCates.map(item => item.cate === cate && item.cate_zh)
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      align: 'center',
      render: create_time => moment(create_time).format('YYYY年M月DD号')
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      render: status => statusArr.map(item => status === item.enum && item.status)
    },
    {
      title: '操作',
      dataIndex: '_id',
      align: 'center',
      render: id => (
        <div className="list-opretion">
          <span onClick={() => delRow(id)}>删除</span>
          <span onClick={() => props.history.push('/dash/article/info?id='+id)}>编辑</span>
        </div>
      )
    }
  ];

  //初始化获取列表
  useEffect(() => {
    dispatch(handleArticleList(formState))
    return undefined
  }, [formState]) 

  useEffect(() => {
    // console.log(delId);
    dispatch(handleArticleList(formState))
    return undefined
  }, [delId])

  //改变查询提交
  const onSelectChange = selectedRowKeys => {
    let newSelectedRowKeys = JSON.parse(JSON.stringify(selectedRowKeys))
    // console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys)
  };
  
  //改变查询条件函数
  const changeForm = (val, type) => {
    // const newFormState = {...formState}
    const newFormState = JSON.parse(JSON.stringify(formState))
    // console.log(val);
    if(type === 'pagination') {
      newFormState['page'] = val.page;
      newFormState['limit'] = val.limit
    }else {
      newFormState[type] = val
    }
    if(type!=='pagination') newFormState['page'] = 1
    // console.log(newFormState);
    setFormState(newFormState)
  }

  //删除
  const delRow = id => {
    dispatch(handleDelArticle(id))

  }

  //表格处理
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: '选中奇数行',
        onSelect: changableRowKeys => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((key, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          setSelectedRowKeys(newSelectedRowKeys)
        },
      },
      {
        key: 'even',
        text: '选中偶数行',
        onSelect: changableRowKeys => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((key, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
          setSelectedRowKeys(newSelectedRowKeys)

        },
      },
    ],
  };
  return (
    <div className="my-article-list">
      <div className="article-query">
        <Divider orientation="left">文章查询</Divider>
        <Row gutter={16} justify="space-around">
          <Col offset={2} className="gutter-row" span={7}>
            <label htmlFor="article-title">文章标题：
              <Input 
              style={{width: '70%'}} 
              allowClear 
              placeholder="请输入文章标题！" 
              id="article-title"
              value={formState.title}
              onChange={e => changeForm(e.target.value, 'title')}
              />
            </label>
          </Col>
          {/* <Col className="gutter-row" span={7}>
            <label htmlFor="article-author">文章作者：<Input style={{width: '70%'}} allowClear placeholder="请输入文章作者！" id="article-author" /></label>
          </Col> */}
          <Col className="gutter-row" span={7}>
            <label htmlFor="article-cate">文章类别：
              <MySelectOptions onChange={val => changeForm(val, 'cate')} value={formState.cate} />
            </label>
          </Col>
          <Col className="gutter-row" span={6}>
            <div className="btns">
              <Button type="primary" onClick={e => setFormState(defaultFormState)}>重置</Button>
            </div>
          </Col>
        </Row>
      </div>
      <div className="article-list">
        <Row className="my-article-list" justify="space-between" style={{margin: '20px 10px 5px'}}>
          <Col>文章列表</Col>
          <Col>
            <Button type="dashed" onClick={() => props.history.push('/dash/article/info')}><PlusOutlined />新增</Button>
          </Col>
        </Row>
        <Table
            rowSelection={{
              type: 'checkbox',
              ...rowSelection
            }}
            rowKey={'_id'}
            columns={columns}
            dataSource={articleList || []}
            pagination={{
              total: articleList.length || 0,
              showSizeChanger: true,
              pageSizeOptions: [3,6,9],
              showTotal: (total, range) => (`第${range[0]}-${range[1]}条 / 总共${total} 条`),
              defaultPageSize: formState.limit,
              defaultCurrent: formState.page,
              current: formState.page,
              onChange: (page,limit)=>changeForm({page,limit},'pagination')
            }}
          />
      </div>
    </div>
  )
}